<template>
  <div>
    <PageDialog
      :title="dialogInfo.title"
      v-model:visible="showDialog"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <div class="layui-row">
        <div class="layui-col-md6 select-depot-storage">
          <!-- 条件栏 -->

          <div class="filter-wrapper">
            <NewPageFilter
              v-model:query="leftFilterInfo.query.queryMap"
              :query-more-json="true"
              :filter-list="leftFilterInfo.searchList"
              :filter-btn="leftFilterInfo.searchBtn"
            >
            </NewPageFilter>
          </div>
          <div class="filter-wrapper flex-end">
            <NewPageFilter :filter-btn="leftFilterInfo.btnList">
              <template v-slot:filter-btn>
                <el-button
                  :disabled="!(leftTableInfo.selections && leftTableInfo.selections.length)"
                  @click="removeRight"
                  >右移</el-button
                >
              </template>
            </NewPageFilter>
          </div> 
          <DialogTable
            ref="leftTableInfoRef"
            :refresh="leftTableInfo.refresh"
            :init-curpage="leftTableInfo.initCurpage"
            v-model:data="leftTableInfo.data"
            :api="leftTableInfo.api"
            :reserve-selection="true"
            :listen-height="false"
            :check-box="true"
            check-box-fixed="right"
            v-model:query="leftFilterInfo.query"
            :field-list="leftTableInfo.fieldList"
            :handle="leftTableInfo.handle"
            @handleEvent="leftHandleEvent"
          >
          </DialogTable>
        </div>
        <div
          class="layui-col-md6 select-depot-storage"
          style="padding-left: 20px"
        >
          <div class="filter-wrapper flex-end">
            <NewPageFilter :filter-list="rightFilterInfo.searchList">
              <template v-slot:filter-productCodeScan>
                <ScanInputBox
                  v-model:query="scanInfo.query"
                  :api="scanInfo.api"
                  @callback="onCallBackScanData"
                />
              </template>
            </NewPageFilter>
          </div>
          <div class="filter-wrapper">
            <NewPageFilter :filter-btn="rightFilterInfo.btnList">
              <template v-slot:filter-removeLeft>
                <el-button
                  :disabled="!(rightTableInfo.selections && rightTableInfo.selections.length)"
                  @click="removeLeft"
                  >左移</el-button
                >
              </template>
              <template v-slot:filter-fill>
                <el-checkbox
                  v-if="info.codeType === 1 || info.codeType === 4"
                  :key="Math.random()"
                  v-model="rightFilterInfo.data.fill"
                  label="一键填充"
                  border
                  @change="changeNumberAll"
                ></el-checkbox>
              </template>
            </NewPageFilter>
          </div>
          <el-form ref="tableForm" :model="rightTableInfo" style="width: 100%">
            <DialogTable
              ref="rightTableInfoRef"
              v-model:data="rightTableInfo.data"
              :reserve-selection="true"
              :listen-height="false"
              :pager="false"
              :check-box="true"
              :field-list="rightTableInfo.fieldList"
              :handle="rightTableInfo.handle"
              :row-class-name="tableRowClassName"
              @handleEvent="rightHandleEvent"
            >
              <template v-slot:col-qty="scope">
                <el-form-item
                  v-if="scope.row.codeType === 1 || scope.row.codeType === 4"
                  :key="scope.$index"
                  class="margin-bottom"
                  @click.stop=""
                >
                  <div class="page-table-input-number-wrapper">
                    <div class="page-table-input-number-left">
                      <div class="page-table-input-number-item">
                        <el-form-item
                          :prop="`data.${scope.$index}.largeUnitQty`"
                          :rules="[
                            {
                              validator: $validate.positiveAndZero,
                              trigger: 'blur',
                            },
                          ]"
                        >
                          <el-input-number
                            v-model.lazy="scope.row.largeUnitQty"
                            style="width: 100%; margintop: 18px"
                            clearable
                            controls-position="right"
                            :precision="
                              scope.row.qtyOperateMode === 0 ||
                              scope.row.qtyOperateMode === 2
                                ? 0
                                : systemConfig.qty_show_precision
                            "
                            :min="0"
                            :max="largeMax(scope.row)"
                            @change="
                              changeLarge(
                                $event,
                                scope.row,
                                `data.${scope.$index}.largeUnitQty`
                              )
                            "
                          />
                        </el-form-item>
                        <div class="page-table-input-number-item-unite">
                          {{ scope.row.unitName }}
                        </div>
                      </div>
                      <div
                        v-if="
                          scope.row.unitConvertCoefficient > 1 &&
                          scope.row.qtyOperateMode === 2
                        "
                        class="page-table-input-number-item"
                      >
                        <el-form-item>
                          <el-input-number
                            v-model.lazy="scope.row.smallUnitQty"
                            style="width: 100%; margintop: 18px"
                            clearable
                            controls-position="right"
                            :precision="0"
                            :min="0"
                            :max="smallMax(scope.row)"
                          />
                        </el-form-item>
                        <div class="page-table-input-number-item-unite">
                          {{ scope.row.calcUnitName }}
                        </div>
                      </div>
                    </div>
                    <div
                      v-if="scope.row.qtyOperateMode === 2"
                      class="page-table-input-number-right"
                    >
                      {{ $fn.qtyFormatter(scope.row.qty) }}
                    </div>
                  </div>
                </el-form-item>
                <span
                  v-else-if="
                    scope.row.codeType === 2 || scope.row.codeType === 3
                  "
                  >{{ $fn.qtyFormatter(scope.row.qty) }}</span
                >
              </template>
              <template v-slot:col-scrapReason="scope">
                <el-input
                  v-model="scope.row.scrapReason"
                  :maxlength="25"
                  @input="(e) => (scope.row.scrapReason = validSe(e))"
                />
              </template>
            </DialogTable>
          </el-form>
        </div>
      </div>
    </PageDialog>
  </div>
</template>

<script setup name="IndividualDetails">
import { getCustomizeSetting } from '@/api/customize'
import ScanInputBox from './ScanInputBox'
const { proxy } = getCurrentInstance()
const props = defineProps({
  scanInfo: {
    type: Object,
    default: function () {
      return {}
    },
  },
  leftApi: {
    type: Function,
  },
  rightApi: {
    type: Function,
  },
  visible: {
    type: Boolean,
  },
  showPrice: {
    type: Boolean,
  },
  rightCustomizeUserVO: {
    type: Object,
    default: function () {
      return {}
    },
  },
  sysGroup: {
    type: Array,
    default: function () {
      return []
    },
  },
  requestRightList: {
    type: Boolean,
    default: false,
  },
  scrapReason: {
    type: Boolean,
    default: false,
  },
  rightVo: {
    type: Object,
    default: function () {
      return {}
    },
  },
  leftQueryObj: {
    type: Object,
    default: function () {
      return {}
    },
  },
  rightQueryObj: {
    type: Object,
    default: function () {
      return {}
    },
  },
  queryParams: {
    type: Object,
    default: function () {
      return {}
    },
  },
  infoList: {
    type: Object,
    default: function () {
      return {}
    },
  },
  leftTableKey: {
    type: String,
    default:
      'beginningAccountExportOrderModifySingleLeft-com.slip.spd.entity.vo.beginning.BeginningDepotStockVO',
  },
})
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const info = ref({})
const checkBox = ref(false)
const selectedScanValue = ref('1')
const scanInput = ref('')
// 过滤相关配置
const leftFilterInfo = ref({
  query: {
    queryMap: {},
    queryParams: {
      stockAvailableCalcQtyGt: 0,
    },
    customizeUserVO: {},
  },
  searchList: [],
  searchBtn: [{ type: 'button', label: '搜索', event: leftSearch }],
  btnList: [{ type: 'slot', value: 'btn' }],
})
// 表格相关
const leftTableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  height: '70%',
  data: [],
  selections: [],
  fieldList: [],
})
const rightTableInfo = ref({
  height: '70%',
  data: [],
  fieldList: [],
  selections: [],
})
const rightFilterInfo = ref({
  data: {
    fill: false,
  },
  searchList: [{ slot: true, value: 'productCodeScan' }],
  btnList: [
    { type: 'slot', value: 'removeLeft' },
    { type: 'slot', value: 'fill' },
  ],
})
const leftQuery = ref({})
const rightQuery = ref({})
// 弹窗相关
const dialogInfo = ref({
  title: '选择个体',
  btLoading: false,
  width: '90%',
  btList: [
    { label: '关闭', event: handleClose, show: true },
    { label: '保存', event: handleSave, show: true },
  ],
})
const selectRow = ref('')
const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    proxy.$emit('update:visible', val) // 更新父组件visible
  },
})
watch(
  () => rightTableInfo.value.data,
  (val) => {
    if (rightTableInfo.value.data && rightTableInfo.value.data.length) {
      val.forEach((row) => {
        let smallUnitQty = parseFloat(row.smallUnitQty || 0)
        let unitConvertCoefficient = parseFloat(row.unitConvertCoefficient || 1)
        let largeUnitQty = parseFloat(row.largeUnitQty || 0)
        let calcQty = proxy.$fn.accAdd(
          proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
          smallUnitQty
        )
        let qty = proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
        row['calcQty'] = calcQty
        row['qty'] = qty
        row.sumAmount = proxy.$fn.accDiv(
          proxy.$fn.accMul(calcQty, parseFloat(row.price)),
          unitConvertCoefficient
        )
      })
    }
  },
  { deep: true }
)
function largeMax(row) {
  if (row.qtyOperateMode === 2) {
    return parseInt(row.stockAvailableCalcQty / row.unitConvertCoefficient)
  } else {
    return row.stockAvailableQty
  }
}
function smallMax(row) {
  let largeUnitQty = parseInt(
    row.stockAvailableCalcQty / row.unitConvertCoefficient
  )
  if (largeUnitQty === 0 || row.largeUnitQty === largeUnitQty) {
    return parseInt(row.stockAvailableCalcQty % row.unitConvertCoefficient)
  } else {
    return row.unitConvertCoefficient - 1
  }
}
function changeLarge(e, row, str) {
  proxy.$refs.tableForm.clearValidate(str)
  let largeUnitQty = parseInt(
    row.stockAvailableCalcQty / row.unitConvertCoefficient
  )
  if (row.qtyOperateMode === 2 && row.unitConvertCoefficient > 1) {
    if (largeUnitQty > 0 && e === largeUnitQty) {
      let smallUnitQty = parseInt(
        row.stockAvailableCalcQty % row.unitConvertCoefficient
      )
      if (row.smallUnitQty > smallUnitQty) {
        row.smallUnitQty = smallUnitQty
      }
    }
  }
}
function changeNumberAll(type) {
  rightTableInfo.value.data.forEach((item) => {
    let unitConvertCoefficient = item.unitConvertCoefficient || 1
    if (type) {
      if (item.codeType === 4 || item.codeType === 1) {
        let num = item.stockAvailableCalcQty
        if (num > 0) {
          item.calcQty = num
          if (item.qtyOperateMode === 2) {
            item.largeUnitQty = parseInt(item.calcQty / unitConvertCoefficient)
            item.smallUnitQty = parseInt(item.calcQty % unitConvertCoefficient)
          } else {
            item.largeUnitQty = item.calcQty
            item.smallUnitQty = 0
          }
        }
      }
    } else {
      item.largeUnitQty = 0
      item.smallUnitQty = 0
    }
  })
}
function leftHandleEvent(event, data) {
  if (event === 'list') {
    data.forEach((item) => {
      item.accountDepotStockId = item.id
    })
    leftTableInfo.value.data = data
  }
  if (event === 'tableCheck') {
    leftTableInfo.value.selections = data
  }
}
function rightHandleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      rightTableInfo.value.selections = data
      break
  }
}
async function onCallBackScanData(data, callback) {
  let { mergeDetail, detail } = data
  let leftItems = leftTableInfo.value.data.filter(
    (item) => item.accountDepotStockId === detail.accountDepotStockId
  )
  let rightItems = rightTableInfo.value.data.filter(
    (item) => item.accountDepotStockId === detail.accountDepotStockId
  )
  if (leftItems.length && !rightItems.length) {
    rightTableInfo.value.data.forEach((item) => {
      item.isChoice = false
    })
    removeRight(detail)
    callback(false)
  } else if (!leftItems.length && rightItems.length) {
    if (rightItems[0].codeType === 2 || rightItems[0].codeType === 3) {
      callback(true)
    } else {
      let item = rightItems[0]
      let unitConvertCoefficient = item.unitConvertCoefficient || 1
      let num = proxy.$fn.Subtr(item.stockAvailableCalcQty, item.calcQty)
      if (num > 0) {
        if (num > unitConvertCoefficient) {
          item.calcQty = proxy.$fn.accAdd(item.calcQty, unitConvertCoefficient)
        } else {
          item.calcQty = proxy.$fn.accAdd(item.calcQty, num)
        }
        if (item.qtyOperateMode === 2) {
          item.largeUnitQty = parseInt(
            item.calcQty / item.unitConvertCoefficient
          )
          item.smallUnitQty = parseInt(
            item.calcQty % item.unitConvertCoefficient
          )
        } else if (item.qtyOperateMode === 0 || item.qtyOperateMode === 1) {
          item.largeUnitQty = item.calcQty
          item.smallUnitQty = 0
        }
        callback(false)
      } else {
        callback(true)
      }
    }
  } else {
    await setInfo()
    await proxy.$emit('callbackSacn', data, info.value, (val) => {
      callback(val)
      if (!val) {
        leftQuery.value = props.leftQueryObj
        rightQuery.value = props.rightQueryObj
        info.value = JSON.parse(JSON.stringify(props.infoList))
        rightTableInfo.value.data = info.value.details
        getleftCustomize()
      }
    })
  }
}
function tableRowClassName({ row = undefined }) {
  if (row.isChoice) {
    return 'success-row'
  } else {
    return ''
  }
}
function getleftList() {
  leftTableInfo.value.refresh = Math.random()
}
function leftSearch() {
  leftTableInfo.value.initCurpage = Math.random()
  leftTableInfo.value.refresh = Math.random()
}
// 关闭弹窗前的回调
function handleClose() {
  showDialog.value = false
  proxy.$emit('reset')
}
async function removeRight(detail = undefined) {
  //左边往右移
  let selections =
    detail && detail.id ? [detail] : leftTableInfo.value.selections
  let selectionsDeoptStockIds = selections.map(
    (item) => item.accountDepotStockId
  )
  let groupConcatIds = proxy.$fn.splitArr(info.value.groupConcatIds)
  let groupConcatAccountDepotStockIds = proxy.$fn.splitArr(
    info.value.groupConcatAccountDepotStockIds
  )
  leftTableInfo.value.data = leftTableInfo.value.data.filter(
    (item) =>
      !selectionsDeoptStockIds.includes(Number(item.accountDepotStockId))
  )
  selections.forEach((row) => {
    if (row.codeType == 1 || row.codeType == 4) {
      if (row.stockAvailableQty <= 1) {
        if (row.qtyOperateMode === 2) {
          row.largeUnitQty = parseInt(
            row.stockAvailableCalcQty / row.unitConvertCoefficient
          )
          row.smallUnitQty = parseInt(
            row.stockAvailableCalcQty % row.unitConvertCoefficient
          )
        } else {
          row.largeUnitQty = row.stockAvailableQty
          row.smallUnitQty = 0
        }
      } else {
        row.largeUnitQty = 1
        row.smallUnitQty = 0
      }
    } else if (row.codeType == 2 || row.codeType == 3) {
      if (row.qtyOperateMode === 2) {
        row.largeUnitQty = parseInt(
          row.stockAvailableCalcQty / row.unitConvertCoefficient
        )
        row.smallUnitQty = parseInt(
          row.stockAvailableCalcQty % row.unitConvertCoefficient
        )
      } else {
        row.largeUnitQty = row.stockAvailableQty
        row.smallUnitQty = 0
      }
    }
  })
  rightTableInfo.value.data = proxy.$fn
    .deepClone(selections)
    .concat(rightTableInfo.value.data)
  groupConcatAccountDepotStockIds = selectionsDeoptStockIds.concat(
    groupConcatAccountDepotStockIds
  )
  groupConcatIds = selectionsDeoptStockIds.concat(groupConcatIds)
  info.value.groupConcatAccountDepotStockIds =
    groupConcatAccountDepotStockIds.toString()
  info.value.groupSize = groupConcatAccountDepotStockIds.length
  leftFilterInfo.value.query.queryMap.id.value =
    groupConcatAccountDepotStockIds.length
      ? groupConcatAccountDepotStockIds.toString()
      : ''
  getleftList()
  proxy.$refs['leftTableInfo'].$children[0].clearSelection()
}
async function removeLeft() {
  //右边往左移
  let selections = rightTableInfo.value.selections
  let selectionsDeoptStockIds = selections.map(
    (item) => item.accountDepotStockId
  )
  let groupConcatIds = proxy.$fn.splitArr(info.value.groupConcatIds)
  let groupConcatAccountDepotStockIds = proxy.$fn.splitArr(
    info.value.groupConcatAccountDepotStockIds
  )
  rightTableInfo.value.data = rightTableInfo.value.data.filter(
    (item) =>
      !selectionsDeoptStockIds.includes(Number(item.accountDepotStockId))
  )
  groupConcatAccountDepotStockIds = groupConcatAccountDepotStockIds.filter(
    (item) => !selectionsDeoptStockIds.includes(Number(item))
  )
  groupConcatIds = groupConcatIds.filter(
    (item) => !selectionsDeoptStockIds.includes(Number(item))
  )
  info.value.details = rightTableInfo.value.data
  info.value.groupConcatAccountDepotStockIds =
    groupConcatAccountDepotStockIds.toString()
  info.value.groupSize = groupConcatAccountDepotStockIds.length
  selections.forEach((item) => {
    item.largeUnitQty = 0
    item.smallUnitQty = 0
    item.calcQty = 0
    item.sumAmount = 0
  })
  leftFilterInfo.value.query.queryMap.id.value =
    groupConcatAccountDepotStockIds.length
      ? groupConcatAccountDepotStockIds.toString()
      : ''
  getleftList()
  proxy.$refs['rightTableInfo'].$children[0].clearSelection()
}
function handleSave() {
  proxy.$refs['tableForm'].validate((valid) => {
    if (valid) {
      setInfo()
      // console.log(info.value)
      // return
      proxy.$emit('callback', info.value)
      handleClose()
    }
  })
}
async function setInfo() {
  let unitConvertCoefficient = parseFloat(
    info.value.unitConvertCoefficient || 1
  )
  let largeUnitQty = 0
  let smallUnitQty = 0
  let calcQty = 0
  let sumAmount = 0
  if (rightTableInfo.value.data.length) {
    info.value.details = rightTableInfo.value.data.filter((item) => {
      largeUnitQty = proxy.$fn.accAdd(largeUnitQty, item.largeUnitQty || 0)
      smallUnitQty = proxy.$fn.accAdd(smallUnitQty, item.smallUnitQty || 0)
      calcQty = proxy.$fn.accAdd(calcQty, item.calcQty || 0)
      sumAmount = proxy.$fn.accAdd(item.sumAmount || 0, sumAmount)
      return item.calcQty > 0
    })
  } else {
    info.value.details = []
  }
  let groupConcatAccountDepotStockIds = info.value.details.length
    ? info.value.details.map((item) => {
        if (item.calcQty > 0) {
          return item.accountDepotStockId
        }
      })
    : ''
  info.value.groupConcatAccountDepotStockIds =
    groupConcatAccountDepotStockIds.length
      ? groupConcatAccountDepotStockIds.toString()
      : ''
  info.value.sumAmount = sumAmount
  info.value.qty = proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
  info.value.calcQty = calcQty
  info.value.smallUnitQty = smallUnitQty
  info.value.largeUnitQty = largeUnitQty
  console.log(info.value)
}
function getleftCustomize() {
  let param = { tableKey: props.leftTableKey }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      leftFilterInfo.value.query.customizeUserVO = data
      leftTableInfo.value.fieldList = proxy.$fn.setFieldList(
        leftTableInfo.value.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        leftFilterInfo.value.searchList,
        data.detail
      )
      leftFilterInfo.value.searchList = searchInfo.searchList
      leftFilterInfo.value.searchList.forEach((item) => {
        item.event = leftSearch
      })
      leftFilterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...leftQuery.value,
      }
      leftTableInfo.value.api = props.leftApi
      getleftList()
    }
  })
}
function getList(data) {
  let param = {
    customizeUserVO: data,
    queryMap: {
      ...rightQuery.value,
    },
    queryParams: {},
  }
  props.rightApi(param).then((resp) => {
    if (resp && resp.success && resp.data.length) {
      let data = resp.data
      info.value.details = data
      rightTableInfo.value.data = data
    }
  })
}
function getrightCustomize() {
  let data = props.rightVo
  rightTableInfo.value.fieldList = proxy.$fn.setFieldList(
    rightTableInfo.value.fieldList,
    data.detail
  )
  rightTableInfo.value.data = info.value.details
  if (props.requestRightList && !info.value.details) {
    getList(data)
  }
}
let obj = {
  price: {
    label: '单价',
    value: 'price',
    type: 'column',
    componentType: 'price',
    permission: !props.showPrice,
    formatter: proxy.$fn.TripartiteMethod,
    show: false,
    hidden: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    type: 'column',
    componentType: 'price',
    permission: !props.showPrice,
    formatter: proxy.$fn.TripartiteMethod,
    show: false,
    hidden: true,
  },
  showPrice: {
    label: '展示价格',
    value: 'showPrice',
    type: 'column',
    componentType: 'price',
    permission: !props.showPrice,
    formatter: proxy.$fn.TripartiteMethod,
    show: false,
    hidden: true,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    permission: !props.showPrice,
    componentType: 'price',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    show: false,
    hidden: true,
  },
  commonName: {
    label: '通用名称',
    value: 'commonName',
    componentType: 'input',
    show: false,
    hidden: true,
  },
}
let scrapReason = props.scrapReason
  ? {
      label: '报废原因',
      value: 'scrapReason',
      minWidth: '150px',
      type: 'slot',
      hidden: true,
    }
  : ''
leftTableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
leftFilterInfo.value.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
rightTableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
  qty: {
    label: '数量',
    value: 'qty',
    type: 'slot',
    minWidth: '250px',
    hidden: true,
  },
  scrapReason,
})
leftQuery.value = props.leftQueryObj
rightQuery.value = props.rightQueryObj
info.value = JSON.parse(JSON.stringify(props.infoList))
leftFilterInfo.value.query.queryParams = {
  ...leftFilterInfo.value.query.queryParams,
  ...props.queryParams,
}
getleftCustomize()
getrightCustomize()
</script>

<style scoped lang="scss"></style>
